# Maintainer: Alexey Pavlov <alexpux@gmail.com>

_realname=perl

pkgname="${MINGW_PACKAGE_PREFIX}-${_realname}"
pkgver=5.18.1
pkgrel=2
pkgdesc="A highly capable, feature-rich programming language (mingw-w64)"
arch=('any')
url="http://www.perl.org"
license=('GPL' 'PerlArtistic')
makedepends=("${MINGW_PACKAGE_PREFIX}-gcc" "${MINGW_PACKAGE_PREFIX}-dmake")
depends=("${MINGW_PACKAGE_PREFIX}-winpthreads")
options=('staticlibs' 'strip' '!purge')
install=perl.install
source=("http://www.cpan.org/src/5.0/perl-${pkgver}.tar.bz2"
    perl-5.18.0-add-missing-mingw-libs.patch
    perl-variables.patch)
md5sums=('4ec1a3f3824674552e749ae420c5e68c'
         '0b4e643fe4c54512d0c5833665e88f5e'
         'b9cfc63845749f8ebddb0219208eed84')

prepare() {
  cd ${srcdir}/${_realname}-${pkgver}
  patch -p1 -i ${srcdir}/perl-5.18.0-add-missing-mingw-libs.patch
  patch -p1 -i ${srcdir}/perl-variables.patch
}

build() {
  cp -r ${srcdir}/${_realname}-${pkgver} ${srcdir}/build-${CARCH}
  cd ${srcdir}/build-${CARCH}/win32
  
  mkdir -p ${pkgdir}${MINGW_PREFIX}
  pushd ${pkgdir}${MINGW_PREFIX} > /dev/null
  export PREFIX_WIN=`pwd -W`
  popd > /dev/null
  
  local DRV=`expr substr $PREFIX_WIN 1 2`
  local NOTDRV=${PREFIX_WIN#$DRV}
  NOTDRV=$(echo $NOTDRV | sed 's|/|\\\\|g')
  local MINGWHOME_WIN_P=$(echo $PREFIX_WIN | sed 's|/|\\\\|g')

  local COMMA=
  local EXTRA=$PREFIX_WIN/${MINGW_CHOST}/lib
  [[ ${CARCH} == i686 ]] && {
    COMMA=""  
  } || {
    COMMA="#"
  }
  EXTRA=$(echo $EXTRA | sed 's|/|\\\\|g')
    
  cat makefile.mk | sed 's|%DRV%|'"$DRV"'|g' \
    | sed -e 's|%NODRV%|'"$NOTDRV"'|g' \
    | sed -e 's|%COMW64%|'"$COMMA"'|g' \
    | sed -e 's|%MINGWHOME%|'"$MINGWHOME_WIN_P"'|g' \
    | sed -e 's|%THIRDPARTY_LIBS%|'"$EXTRA"'|g' > makefile.tmp

  rm -f makefile.mk
  mv makefile.tmp makefile.mk
  
  pushd $SYSTEMROOT > /dev/null
  local WIN_SYS=`pwd`
  popd > /dev/null
  local WINDOWS_PART_PATH=$WIN_SYS/system32:$WIN_SYS
  unset SHELL
    PATH=${MINGW_PREFIX}/bin:${WINDOWS_PART_PATH}:${PATH} ${MINGW_PREFIX}/bin/dmake
}

package() {
    cd "${srcdir}/build-${CARCH}/win32"
  pushd $SYSTEMROOT > /dev/null
  local WIN_SYS=`pwd`
  popd > /dev/null
  local WINDOWS_PART_PATH=$WIN_SYS/system32:$WIN_SYS
    PATH=${MINGW_PREFIX}/bin:${WINDOWS_PART_PATH}:${PATH} ${MINGW_PREFIX}/bin/dmake install
  
  # fix permissions
  find ${pkgdir}${MINGW_PREFIX} -type f \( -name "*.bat" -o -name "*.dll" -o -name "*.exe" \) | xargs chmod 0755
  find ${pkgdir}${MINGW_PREFIX} -type f \( -name "*.a" -o -name "*.pm" -o -name "*.pl" -o -name "*.h" \) | xargs chmod 0644

  mkdir -p ${pkgdir}${MINGW_PREFIX}
  pushd ${pkgdir}${MINGW_PREFIX} > /dev/null
  export PREFIX_WIN=`pwd -W`
  popd > /dev/null
  PREFIX_WIN=${PREFIX_WIN//\//\\\\\\\\}
  
  echo "RELOCATE is ${PREFIX_WIN}"
  sed -i "s|${PREFIX_WIN}|%RELOCATE%|g" \
    ${pkgdir}${MINGW_PREFIX}/lib/Config.pm \
    ${pkgdir}${MINGW_PREFIX}/lib/Config_heavy.pl \
    ${pkgdir}${MINGW_PREFIX}/lib/CORE/config.h
}
